﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;
using System.Collections;
using System.Data.SqlClient;

namespace Media.Core.Helpers.Main
{
    public class ImageGrabber
    {
        public static string GetAndSave(string url, string Folder, string Title, string Type)
        {
            WebClient webclient = new WebClient(); //Starts the webclient for downloading a file from a url
            string saveLocation = ""; //Where to save the file downloaded

            Title = CheckTitle(Title);
            Folder = CheckTitle(Folder);
            string extensionType = GetExtension(url);

            ArrayList paramsList;
            paramsList = new ArrayList { new SqlParameter("Type", Type) };
            var drSaveLocation = Data.Connections.GetDataRow("Main_Get_SaveLocation", paramsList);

            var DirectoryLocation = TvCreateDirectory(drSaveLocation["Location"].ToString(), Folder, Type);

            //Downloads the file and uses the variabels for url, correctlocation, title, and extension type.
            webclient.DownloadFile(url, DirectoryLocation + Title + extensionType);

            return Folder + "/" + Type + "/" + Title + extensionType;

        }


        public static string TvCreateDirectory(string url, string Folder, string Type)
        {
            string CreateDirectoryPath = url + "\\" + Folder + "\\" + Type + "\\";

            // Determine whether the directory exists.
            if (Directory.Exists(CreateDirectoryPath))
            {
                //Console.WriteLine("That path exists already.");
                return CreateDirectoryPath;
            }
            else
            {
                // Try to create the directory.
                DirectoryInfo di = Directory.CreateDirectory(CreateDirectoryPath);
                //Console.WriteLine("The directory was created successfully at {0}.", Directory.GetCreationTime(CreateDirectoryPath));
                return CreateDirectoryPath;
            }
        }

        public static string GetExtension(string url)
        {
            int startExtension = 0; //Finds what extension needs to be put on the end of the file.
            //Goes from the end of the url till it finds the first point ('.') and then you use that number for getting the substring
            for (int i = url.Length - 1; i >= 0; i--)
            {
                if (url[i] == '.')
                {
                    startExtension = i;
                    break;
                }
            }
            //goes from the number from the for loop till the end of the string. Should be the extension
            return url.Substring(startExtension);
        }


        public static string CheckTitle(string title)
        {
            char[] unusables = new char[]
            {
                '/','\\','*','"','?',':','>','<','|'
            };

            for (int i = 0; i < title.Length; i++)
            {
                for (int j = 0; j < unusables.Length; j++)
                {
                    if (title[i] == unusables[j])
                    {
                        title = title.Replace(unusables[j], '-');
                    }
                }
            }

            return title;
        }

        //OLD NOT IN USE AT THE MOMENT
        static public void GetBytesFromUrl(string url, string Title, string Type = "Movie")
        {
            string imageUrl = url;
            string saveLocation = ("../../Content/MovieImages/" + Title + ".jpg");

            byte[] imageBytes;
            HttpWebRequest imageRequest = (HttpWebRequest)WebRequest.Create(imageUrl);
            WebResponse imageResponse = imageRequest.GetResponse();

            Stream responseStream = imageResponse.GetResponseStream();

            using (BinaryReader br = new BinaryReader(responseStream))
            {
                imageBytes = br.ReadBytes(500000);
                br.Close();
            }
            responseStream.Close();
            imageResponse.Close();

            FileStream fs = new FileStream(saveLocation, FileMode.Create);
            BinaryWriter bw = new BinaryWriter(fs);
            try
            {
                bw.Write(imageBytes);
            }
            finally
            {
                fs.Close();
                bw.Close();
            }
        }
    }
}